<?php
/**
 * Created by JetBrains PhpStorm.
 * User: shaoshuai
 * Date: 12-7-15
 * Time: 下午9:08
 * To change this template use File | Settings | File Templates.
 */
class OnlineList
{
    const FILE = 'online.list.txt';
    /**
     * @var OnlineList
     */
    private static $instance;

    /**
     * @var array
     */
    private $list;

    /**
     * @static
     * @return OnlineList
     */
    public static function getInstance()
    {
        if (!isset(self::$instance)) {
            $class = __CLASS__;
            self::$instance = new $class;
        }
        return self::$instance;
    }

    private function __construct()
    {
        $this->list = array();
        $this->readList();
    }

    private function readList()
    {
        if (!file_exists(OnlineList::FILE)) {
            file_put_contents(OnlineList::FILE, '[]');
            $this->list = array();
        } else {
            $this->list = json_decode(file_get_contents(OnlineList::FILE), true);
        }
    }

    /**
     * @param User $user
     * @return OnlineList
     */
    public function addUser(User $user)
    {
        if (!in_array($user->getName(), $this->list)) {
            array_push($this->list, $user->getName());
        }
        $this->save();
        return $this;
    }

    /**
     * @param User $user
     * @return OnlineList
     */
    public function removeUser(User $user)
    {
        $index = array_search($user->getName(), $this->list);
        if ($index !== false) {
            unset($this->list[$index]);
            $this->list = array_values($this->list);
            $this->save();
        }
        return $this;
    }

    private function save()
    {
        file_put_contents(OnlineList::FILE, json_encode($this->list));
    }

    /**
     * @return array
     */
    public function getList()
    {
        return $this->list;
    }
}
